package com.company.project.controller;
import com.company.project.core.Result;
import com.company.project.core.ResultCode;
import com.company.project.core.ResultGenerator;
import com.company.project.model.AdminLog;
import com.company.project.model.Cart;
import com.company.project.model.Food;
import com.company.project.model.OrderComment;
import com.company.project.model.request.QueryParams;
import com.company.project.service.AdminUserService;
import com.company.project.service.FoodService;
import com.company.project.service.OrderCommentService;
import com.company.project.utils.ImageBinary;
import com.company.project.utils.UploadUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Condition;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
* Created by CodeGenerator on 2020/04/21.
*/
@RestController
@RequestMapping("/food")
public class FoodController {
    @Resource
    private FoodService foodService;
    @Autowired
    private AdminUserService adminUserService;
    @Resource
    private RedisTemplate redisTemplate;
    @Autowired
    private OrderCommentService orderCommentService;

    /**
     * 加入购物车
     */
    @PostMapping("/join/cart")
    public Result joinCart(@RequestBody Cart param) {
        String foodId = param.getFoodId().toString();
        Integer userId = param.getUserId();
        if(StringUtils.isEmpty(foodId)) {
            return ResultGenerator.genFailResult("未选择");
        }
        Object user = redisTemplate.opsForValue().get(userId);
        // 未登录
        if (user == null) {
            List<String> cart=(List<String>)redisTemplate.opsForList().leftPop("cart");
            if(cart == null) {
                cart = new ArrayList<>();
            }
            if(!cart.contains(foodId)) {
                cart.add(foodId);
            }
            redisTemplate.opsForList().leftPush("cart", cart);
            redisTemplate.expire("cart", 2, TimeUnit.HOURS);
            return ResultGenerator.genSuccessResult();
        }
        // 已登录
        List<String> cart = null;
        if(redisTemplate.hasKey(userId.toString())) {
            cart = (List<String>)redisTemplate.opsForList().leftPop(userId.toString());
        }
        if(cart == null) {
            cart = new ArrayList<>();
        }
        if(!cart.contains(foodId)) {
            cart.add(foodId);
        }
        redisTemplate.opsForList().leftPush(userId.toString(), cart);
        return ResultGenerator.genSuccessResult();
    }

    /**
     * 获取购物车列表
     */
    @GetMapping("/get/cart/{id}")
    public Result getCart(@PathVariable("id") Integer userId) {
        List<String> cart = new ArrayList<>();
        Result result = new Result();
        result.setMessage("SUCCESS");
        if(userId == 0 || userId == null) {
            if(redisTemplate.hasKey("cart")) {
                cart = (List<String>) redisTemplate.opsForList().leftPop("cart");
                redisTemplate.opsForList().leftPush("cart", cart);
            }
            result.setCode(ResultCode.NOT_LOGIN);
        } else {
            Object o = redisTemplate.opsForValue().get(userId);
            if(o != null && redisTemplate.hasKey(userId.toString())) {
                cart=(List<String>)redisTemplate.opsForList().leftPop(userId.toString());
                redisTemplate.opsForList().leftPush(userId.toString(), cart);
                result.setCode(ResultCode.SUCCESS);
            } else {
                cart=(List<String>)redisTemplate.opsForList().leftPop(userId.toString());
                redisTemplate.opsForList().leftPush(userId.toString(), cart);
                result.setCode(ResultCode.LOGIN_EXPIRED);
            }

        }
        if(cart == null || cart.size() == 0) {
            return ResultGenerator.genFailResult("购物车为空");
        }
        List<Food> foodList = new ArrayList<>();
        for(String foodId : cart) {
            Food food = foodService.findBy("foodId", Integer.parseInt(foodId));
            foodList.add(food);
        }
        result.setData(foodList);
        return result;
    }

    @PostMapping("/delCartFood")
    public Result delCartFood(@RequestBody Cart cart) {
        if(cart == null || cart.getFoodId() == null) {
            return ResultGenerator.genFailResult("参数有误");
        }
        return foodService.delCartFood(cart);
    }

    @PostMapping("/addOrUpdateFood")
    public Result add(@RequestBody Food food) {
        if(food.getFoodId() != null && food.getFoodId() != 0) {
            return foodService.updateFood(food);
        } else {
            return foodService.add(food);
        }
    }

    @PostMapping("/admin/list")
    public Result adminList(@RequestBody QueryParams queryParams) {
        if(queryParams == null) {
            return ResultGenerator.genFailResult("参数错误");
        }
        return foodService.list(queryParams);
    }

    @GetMapping("/comment/{id}")
    public Result getComment(@PathVariable("id") Integer foodId){
        if(foodId == null || foodId == 0) {
            return ResultGenerator.genFailResult("参数错误");
        }
        Condition condition = new Condition(OrderComment.class);
        condition.createCriteria().andEqualTo("foodId", foodId);
        List<OrderComment> orderIds = orderCommentService.findByCondition(condition);
        List<List<OrderComment>> res = new ArrayList<>();
        for(OrderComment orderComment : orderIds) {
            List<OrderComment> list = orderCommentService.findComments(orderComment.getOrderId());
            List<OrderComment> list2 = list.stream().filter(orderComment1 -> orderComment1.getReply() != null).collect(Collectors.toList());
            if(list2.size() > 0) {
                res.add(list2);
            }
        }
        return ResultGenerator.genSuccessResult(res);
    }

    @PostMapping("/removeAll")
    public Result removeAll(@RequestBody List<Food> foodList) {
        for(Food food : foodList) {
            foodService.deleteOne(food);
        }
        return ResultGenerator.genSuccessResult();
    }

    @PostMapping("/reply/remove")
    public Result deleteReply(@RequestBody Integer id) {
        OrderComment order = orderCommentService.findById(id);
        order.setReply("");
        orderCommentService.update(order);
        return ResultGenerator.genSuccessResult();
    }

    @PostMapping("/reply/add")
    public Result addReply(@RequestBody OrderComment order) {
        OrderComment entity = orderCommentService.findById(order.getId());
        entity.setReply(order.getReply());
        orderCommentService.update(order);
        return ResultGenerator.genSuccessResult();
    }

    @RequestMapping("/upload")
    public Result upload(MultipartFile file, HttpServletResponse response) {
        if (file.isEmpty()) {
            return ResultGenerator.genFailResult("");
        }
        // 拿到文件名
        String filename = file.getOriginalFilename();
        // 存放上传图片的文件夹
        File fileDir = UploadUtils.getImgDirFile();
        // 输出文件夹绝对路径  -- 这里的绝对路径是相当于当前项目的路径而不是“容器”路径
        System.out.println(fileDir.getAbsolutePath());
        try {
            // 构建真实的文件路径
            File newFile = new File(fileDir.getAbsolutePath() + File.separator + filename);
            file.transferTo(newFile);
            String base64 = ImageBinary.getImageBinary(newFile);
            return ResultGenerator.genSuccessResult(base64);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ResultGenerator.genFailResult("");
    }
}
